//搜索模块的所有请求

import { ApiResponse, Article } from '@/types/data'
import { RootAction, RootThunkAction } from '@/types/store'
import { removeHistory, setHistory } from '@/utils/history'
import http from '@/utils/request'

// todo 搜索模块的请求action
export function getSuggestion(keyword: string): RootThunkAction {
  return async (dispatch) => {
    // 关键字为空 直接return
    if (!keyword.trim()) return
    const res = await http.get<ApiResponse<{ options: string[] }>>(
      '/suggestion',
      {
        params: {
          q: keyword,
        },
      }
    )
    // console.log('获取的建议数据', res.data.data.options)
    dispatch({
      type: 'search/set_suggestion',
      payload: res.data.data.options,
    } as RootAction)
  }
}

// todo 处理搜索历史 同步搜索历史到仓库 本地
export function handleSearchHistoy(val: string): RootThunkAction {
  return async (dispatch, getState) => {
    // 先获取原来的数据
    let historyList = getState().search.history

    // 去重
    historyList = historyList.filter((item) => item !== val)
    // 将搜索关键字反骨数组的最前面
    historyList = [val, ...historyList]

    // 限制搜索关键字放入数组的最前面
    if (historyList.length > 10) {
      historyList.pop()
    }

    // 需求: 需要将val 进行处理一下, 去重, 最新的数据在最前面展示
    dispatch({
      type: 'search/set_history',
      payload: historyList,
    } as RootAction)

    setHistory(historyList)
    // console.log('historyList', historyList)
  }
}

// todo 统一处理清空本地数据和仓库数据
export function clearSearchHistory(): RootThunkAction {
  return async (dispatch) => {
    dispatch({
      type: 'search/clear_history',
    } as RootAction)

    removeHistory()
  }
}

// todo 获取每页的搜索结果
export function getSearchResults(
  keyword: string,
  page: number = 1,
  per_page: number = 10
): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<
      ApiResponse<{
        page: number
        per_page: number
        results: Article[]
        total_count: number
      }>
    >('/search', {
      params: {
        q: keyword,
        page,
        per_page,
      },
    })
    console.log('获取的文章 ', res.data.data.results)

    dispatch({
      type: 'search/set_results',
      payload: res.data.data.results,
    } as RootAction)
  }
}
